package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.SServiceOrderTrailTypeEnum;
import cn.huiyunche.base.service.enums.WaybillStatusEnum;
import cn.huiyunche.base.service.interfaces.BAreaService;
import cn.huiyunche.base.service.interfaces.CWaybillService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.interfaces.WaybillTrailService;
import cn.huiyunche.base.service.mappers.CWaybillDetailMapper;
import cn.huiyunche.base.service.mappers.CWaybillTrailMapper;
import cn.huiyunche.base.service.mappers.SServiceOrderTrailMapper;
import cn.huiyunche.base.service.mappers.ext.WaybillTrailExtMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.vo.BAreaSearchVo;
import cn.huiyunche.base.service.vo.UserShowVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WaybillTrailServiceImpl implements WaybillTrailService {

    private static final Logger logger = LoggerFactory.getLogger(WaybillTrailServiceImpl.class);

    @Autowired
    private CWaybillService waybillService = null;

    @Autowired
    private CWaybillTrailMapper cWaybillTrailMapper = null;

    @Autowired
    private WaybillTrailExtMapper waybillTrailExtMapper = null;

    @Autowired
    private CWaybillDetailMapper cWaybillDetailMapper = null;

    @Autowired
    private UserService userService = null;

    @Autowired
    private SServiceOrderTrailMapper sServiceOrderTrailMapper = null;

    @Autowired
    private BAreaService bAreaService = null;

    public void add(CWaybillTrail waybillTrail) throws Exception {
        UserShowVo user = this.getUserService().getCurrentUser();
        if (null == user) {
            logger.error("select user info error");
            throw new BusinessException("未找到当前用户信息");
        }
        waybillTrail.setDriverId(user.getId());
        waybillTrail.setDriverName(user.getRealName());

        //查询运单信息，保存位置信息
        //添加运单信息
        List<Integer> statusList = new ArrayList<Integer>();
        statusList.add(WaybillStatusEnum.ALREADYBID.getValue());
        statusList.add(WaybillStatusEnum.WAITEXTRACTED.getValue());
        statusList.add(WaybillStatusEnum.EXTRACTED.getValue());
        statusList.add(WaybillStatusEnum.WAITSTART.getValue());
        statusList.add(WaybillStatusEnum.WAITCOMPLETE.getValue());
//		statusList.add(WaybillStatusEnum.COMPLETED.getValue());
        List<CWaybill> waybills = this.getWaybillService().selectByUseridAndStatus(user.getId(), statusList);

        // 未查询到运单信息只保存位置信息
        if (null == waybills || waybills.size() == 0) {
            logger.info("add waybill trail,not find waybill. params:{}", waybillTrail);
            this.getcWaybillTrailMapper().insertSelective(waybillTrail);
        } else {
            logger.info("add waybill trail,waybill:{}", JSON.toJSONString(waybills));
            List<CWaybillTrail> waybillTrails = new ArrayList<CWaybillTrail>();
            List<CWaybillTrail> isNotExit = new ArrayList<CWaybillTrail>();
            for (int i = 0; i < waybills.size(); i++) {
                CWaybill waybill = waybills.get(i);
                CWaybillTrail cWaybillTrail = new CWaybillTrail();
                BeanUtils.copyProperties(cWaybillTrail, waybillTrail);
                cWaybillTrail.setOrderId(waybill.getOrderId());
                cWaybillTrail.setWaybillId(waybill.getId());
                waybillTrails.add(cWaybillTrail);
            }
            // 判断是否重复上报地理位置
            for (int i = 0; i < waybillTrails.size(); i++) {
                CWaybillTrailExample example = new CWaybillTrailExample();
                example.createCriteria().andDriverIdEqualTo(waybillTrails.get(i).getDriverId()).andWaybillIdEqualTo(waybillTrails.get(i).getWaybillId()).andLatitudeEqualTo(waybillTrails.get(i).getLatitude()).andLongitudeEqualTo(waybillTrails.get(i).getLongitude());
                List<CWaybillTrail> trails = this.getcWaybillTrailMapper().selectByExample(example);
                if (CollectionUtils.isEmpty(trails)) {
                    isNotExit.add(waybillTrails.get(i));
                }
            }
            List<SServiceOrderTrail> trails = new ArrayList<SServiceOrderTrail>();
            if (CollectionUtils.isNotEmpty(isNotExit)) {
                this.getWaybillTrailExtMapper().batchInsertWaybillTrails(isNotExit);
                // 获取服务订单
                for (CWaybillTrail cWaybillTrail : isNotExit) {
                    CWaybillDetailExample example = new CWaybillDetailExample();
                    example.createCriteria().andWaybillIdEqualTo(cWaybillTrail.getWaybillId());
                    List<CWaybillDetail> cWaybillDetails = this.getCWaybillDetailMapper().selectByExample(example);
                    if (CollectionUtils.isNotEmpty(cWaybillDetails)) {
                        for (CWaybillDetail cWaybillDetail : cWaybillDetails) {
                            if (cWaybillDetail.getServiceDispatchTimes() == 1) {
                                SServiceOrderTrail trail = new SServiceOrderTrail();
                                trail.setCreateTime(new Date());
                                if (StringUtils.isNotBlank(cWaybillTrail.getAddr())) {
                                    trail.setInfo(cWaybillTrail.getAddr());
                                } else {
                                    if (StringUtils.isNotBlank(cWaybillTrail.getCityCode())) {
                                        List<BAreaSearchVo> vos = this.getBAreaService().selectBArea(cWaybillTrail.getCityCode(), null, null);
                                        if (CollectionUtils.isNotEmpty(vos)) {
                                            trail.setInfo(vos.get(0).getpName());
                                        }
                                    }
                                }
                                trail.setServiceOrderId(cWaybillDetail.getServiceOrderId());
                                trail.setStatus(0);
                                trail.setType(SServiceOrderTrailTypeEnum.SERVICE_ORDER_ADDR.getValue());
                                trails.add(trail);
                            }
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(trails)) {
                    for (SServiceOrderTrail sServiceOrderTrail : trails) {
                        logger.info("insert into ServiceOrderTrail params: {}", JSONObject.toJSONString(sServiceOrderTrail));
                        this.getSServiceOrderTrailMapper().insert(sServiceOrderTrail);
                    }
                }
            }
            logger.info("add waybill trail,waybillTrails:{}", JSON.toJSONString(waybillTrails));
        }
    }

    @Override
    public List<CWaybillTrail> selectByid(Long waybillID) {
        CWaybillTrailExample cWaybillTrailExample = new CWaybillTrailExample();
        cWaybillTrailExample.setOrderByClause("id desc");
        cWaybillTrailExample.setLimitStart(0);
        cWaybillTrailExample.setLimitEnd(1);
        cWaybillTrailExample.createCriteria().andWaybillIdEqualTo(waybillID);
        return this.getcWaybillTrailMapper().selectByExample(cWaybillTrailExample);
    }

    private CWaybillService getWaybillService() {
        return this.waybillService;
    }

    private CWaybillTrailMapper getcWaybillTrailMapper() {
        return this.cWaybillTrailMapper;
    }

    private UserService getUserService() {
        return this.userService;
    }

    private WaybillTrailExtMapper getWaybillTrailExtMapper() {
        return this.waybillTrailExtMapper;
    }

    private CWaybillDetailMapper getCWaybillDetailMapper() {
        return this.cWaybillDetailMapper;
    }

    private SServiceOrderTrailMapper getSServiceOrderTrailMapper() {
        return this.sServiceOrderTrailMapper;
    }

    private BAreaService getBAreaService() {
        return this.bAreaService;
    }
}
